import Phaser from 'phaser'
import { SoundUtils } from '../utils/SoundUtils.js';
import { ResponsiveUtils } from '../utils/ResponsiveUtils.js';

export class MainScene extends Phaser.Scene {
  currentMode= 'mode_a'
  rangeMode= 'yi' // yi: 至亿, shiyi: 至十亿, baiyi: 至百亿
  totalRounds= 10
  soundEnabled= true
  teacherBar!: Phaser.GameObjects.Container
  isTeacherBarVisible= true
  activeSceneKey= null
  mainUI!: Phaser.GameObjects.Container
  topHandle!: Phaser.GameObjects.Text
  menuToggleBtn!: Phaser.GameObjects.Text
  responsive!: ResponsiveUtils

  constructor() {
    super('MainScene')
  }

  create() {
    console.log('MainScene created')

    // 让本场景相机背景透明，避免遮挡子场景内容
    this.cameras.main.setBackgroundColor('rgba(0,0,0,0)')


    // 初始化响应式系统
    this.responsive = ResponsiveUtils.getInstance()
    this.responsive.init(this)

    // 设置窗口大小变化监听
    this.scale.on('resize', this.handleResize, this)

    // 创建教师工具条
    this.createTeacherBar()

    // 创建主界面
    this.createMainUI()

    // 设置输入监听
    this.setupInputHandlers()

    // 添加调试信息
    console.log('TeacherBar created at:', this.teacherBar.x, this.teacherBar.y)
    console.log('TeacherBar visible:', this.teacherBar.visible)
    console.log('TeacherBar depth:', this.teacherBar.depth)

    // 启动调试场景（在开发模式下）
    if (process.env.NODE_ENV === 'development') {
      this.scene.launch('DebugScene')
    }

    // 自动启动默认模式
    this.switchToMode(this.currentMode)
  }

  createTeacherBar() {
    this.teacherBar = this.add.container(0, 0)
    this.teacherBar.setDepth(10000)



    // 背景 - 使用更明显的颜色和完全不透明
    const bg = this.add.rectangle(640, 30, 1280, 60, 0xFF0000, 1.0) // 临时用红色背景便于调试
    this.teacherBar.add(bg)

    // 模式按钮
    const modes = [
      { text: '黑洞纠错台', key: 'mode_a', x: 120 },
      { text: '单位跃迁台', key: 'mode_b', x: 280 },
      { text: '星际对比跳', key: 'mode_c', x: 440 }
    ]

    modes.forEach(mode => {
      const btn = this.add.text(mode.x, 30, mode.text, {
        fontSize: '18px',
        color: '#D9E8FF',
        backgroundColor: '#2D3748',
        padding: { x: 12, y: 6 }
      }).setInteractive({ useHandCursor: true })

      btn.on('pointerdown', () => this.switchToMode(mode.key))
      btn.on('pointerover', () => btn.setStyle({ backgroundColor: '#4A5568' }))
      btn.on('pointerout', () => btn.setStyle({ backgroundColor: '#2D3748' }))

      this.teacherBar.add(btn)
    })

    // 范围选择 - 重新设计布局，确保不重叠
    const rangeLabel = this.add.text(500, 20, '范围:', { fontSize: '16px', color: '#D9E8FF' })
    this.teacherBar.add(rangeLabel)

    const ranges = [
      { text: '至亿', key: 'yi', x: 550 },
      { text: '至十亿', key: 'shiyi', x: 610 },
      { text: '至百亿', key: 'baiyi', x: 680 }
    ]

    ranges.forEach(range => {
      const btn = this.add.text(range.x, 30, range.text, {
        fontSize: '14px',
        color: this.rangeMode === range.key ? '#FDE047' : '#D9E8FF',
        backgroundColor: this.rangeMode === range.key ? '#374151' : '#2D3748',
        padding: { x: 10, y: 5 }
      }).setInteractive({ useHandCursor: true })

      // 存储按钮引用以便后续更新
      btn.setData('rangeKey', range.key)

      // 添加明显的悬停效果
      btn.on('pointerover', () => {
        if (this.rangeMode !== range.key) {
          btn.setStyle({
            backgroundColor: '#059669',
            color: '#FFFFFF'
          })
        }
      })
      btn.on('pointerout', () => {
        if (this.rangeMode !== range.key) {
          btn.setStyle({
            backgroundColor: '#2D3748',
            color: '#D9E8FF'
          })
        }
      })

      btn.on('pointerdown', () => {
        console.log('Range button clicked:', range.key)
        this.setRangeMode(range.key)
      })
      this.teacherBar.add(btn)
    })

    // 轮次数量设置 - 重新定位，确保在屏幕范围内
    const roundsLabel = this.add.text(760, 20, '轮次:', { fontSize: '16px', color: '#D9E8FF' })
    this.teacherBar.add(roundsLabel)

    const roundsValues = [5, 10, 15]
    roundsValues.forEach((val, idx) => {
      const btn = this.add.text(810 + idx * 45, 30, String(val), {
        fontSize: '14px',
        color: this.totalRounds === val ? '#FDE047' : '#D9E8FF',
        backgroundColor: this.totalRounds === val ? '#374151' : '#2D3748',
        padding: { x: 10, y: 5 }
      }).setInteractive({ useHandCursor: true })

      // 存储按钮值以便后续更新
      btn.setData('roundsValue', val)

      // 添加明显的悬停效果
      btn.on('pointerover', () => {
        if (this.totalRounds !== val) {
          btn.setStyle({
            backgroundColor: '#059669',
            color: '#FFFFFF'
          })
        }
      })
      btn.on('pointerout', () => {
        if (this.totalRounds !== val) {
          btn.setStyle({
            backgroundColor: '#2D3748',
            color: '#D9E8FF'
          })
        }
      })

      btn.on('pointerdown', () => {
        console.log(`Rounds button clicked: ${val}`)
        this.setRounds(val)
      })
      this.teacherBar.add(btn)
    })

    // 快捷键按钮
    const fullscreenBtn = this.add.text(980, 30, 'F11全屏', { fontSize: '12px', color: '#D9E8FF', backgroundColor: '#2D3748', padding: { x: 6, y: 2 } }).setOrigin(0.5)
    const soundBtn = this.add.text(1050, 30, '空格静音', { fontSize: '12px', color: '#D9E8FF', backgroundColor: '#2D3748', padding: { x: 6, y: 2 } }).setOrigin(0.5)
    const helpBtn = this.add.text(1120, 30, 'H帮助', { fontSize: '12px', color: '#FDE047', backgroundColor: '#374151', padding: { x: 6, y: 2 } }).setOrigin(0.5)

    fullscreenBtn.setInteractive({ useHandCursor: true }).on('pointerdown', () => this.toggleFullscreen())
    soundBtn.setInteractive({ useHandCursor: true }).on('pointerdown', () => this.toggleSound())
    helpBtn.setInteractive({ useHandCursor: true }).on('pointerdown', () => this.showHelp())

    // 键盘快捷键
    this.input.keyboard?.on('keydown-F11', (e) => { e.preventDefault(); this.toggleFullscreen() })
    this.input.keyboard?.on('keydown-SPACE', (e) => { e.preventDefault(); this.toggleSound() })
    this.input.keyboard?.on('keydown-H', (e) => { e.preventDefault(); this.showHelp() })

    this.teacherBar.add([fullscreenBtn, soundBtn, helpBtn])
  }

  createMainUI() {
    this.mainUI = this.add.container(0, 0)

    const title = this.add.text(640, 200, '星际数位跃迁', { fontSize: '48px', color: '#D9E8FF', fontFamily: 'Arial, sans-serif' }).setOrigin(0.5)
    const sub = this.add.text(640, 280, '四年级大数认知游戏', { fontSize: '24px', color: '#9CA3AF', fontFamily: 'Arial, sans-serif' }).setOrigin(0.5)
    const hint = this.add.text(640, 400, '教师工具条应显示在顶部', { fontSize: '18px', color: '#6B7280', fontFamily: 'Arial, sans-serif' }).setOrigin(0.5)

    // 添加一个明显的测试按钮来验证 MainScene 是否可见
    const testBtn = this.add.text(640, 500, '点击测试 MainScene 可见性', {
      fontSize: '20px',
      color: '#FDE047',
      backgroundColor: '#DC2626',
      padding: { x: 20, y: 10 }
    }).setOrigin(0.5).setInteractive({ useHandCursor: true })

    testBtn.on('pointerdown', () => {
      console.log('MainScene test button clicked!')
      alert('MainScene 可见且可交互')
    })

    this.mainUI.add([title, sub, hint, testBtn])
  }

  setupInputHandlers() {
    // 顶部提示手柄 + 固定开关
    this.topHandle = this.add.text(10, 2, '移动到此区域展开教师工具条 ↑', { fontSize: '14px', color: '#9CA3AF', backgroundColor: '#1f2937' }).setDepth(20000)
    this.menuToggleBtn = this.add.text(1180, 2, '固定/隐藏', { fontSize: '14px', color: '#9CA3AF', backgroundColor: '#1f2937' }).setDepth(20000).setInteractive({ useHandCursor: true })

    let pinned = true
    const refreshBar = (show) => {
      if (pinned) show = true
      if (show === this.isTeacherBarVisible) return
      this.isTeacherBarVisible = show
      this.tweens.add({ targets: this.teacherBar, y: show ? 0 : -60, duration: 180, ease: 'Power2' })
      this.topHandle.setVisible(!show)
    }
    this.menuToggleBtn.on('pointerdown', () => { pinned = !pinned; refreshBar(true) })

    // 鼠标移动检测（显示/隐藏教师工具条）
    this.input.on('pointermove', (pointer: Phaser.Input.Pointer) => { refreshBar(pointer.y < 40) })
    this.input.on('pointerdown', (pointer: Phaser.Input.Pointer) => { if (pointer.y < 40) refreshBar(true) })

    // 键盘快捷键
    this.input.keyboard?.on('keydown-F11', (e) => { e.preventDefault(); this.toggleFullscreen() })
    this.input.keyboard?.on('keydown-SPACE', (e) => { e.preventDefault(); this.toggleSound() })
    this.input.keyboard?.on('keydown-H', (e) => { e.preventDefault(); this.showHelp() })

    // 小组竞赛全局键盘控制
    this.setupGlobalKeyboardControls()

    // 初始显示
    this.teacherBar.y = 0
  }

  setupGlobalKeyboardControls() {
    let activeGroupIndex = 0

    this.input.keyboard?.on('keydown', (e) => {
      // 数字键1-7选择队伍
      if (e.key >= '1' && e.key <= '7') {
        activeGroupIndex = Number(e.key) - 1
        console.log('Selected group index:', activeGroupIndex)
        console.log('Active scene key:', this.activeSceneKey)

        // 通知当前活跃场景更新选中的队伍
        if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
          const activeScene = this.scene.get(this.activeSceneKey) as any
          console.log('Active scene found:', activeScene)
          console.log('GroupBar exists:', !!activeScene?.groupBar)
          if (activeScene && activeScene.groupBar) {
            activeScene.groupBar.setActiveIndex(activeGroupIndex)
            console.log('Set active group index to:', activeGroupIndex)
          }
        }
      }

      // F/S/E键加分（只在非组合键时）
      if (!(e.metaKey || e.ctrlKey)) {
        const keys = ['red','orange','yellow','green','cyan','blue','purple']
        const team = keys[activeGroupIndex] as any

        if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
          const activeScene = this.scene.get(this.activeSceneKey) as any
          if (activeScene && activeScene.groupBar) {
            if (e.key.toLowerCase() === 'f') {
              console.log('F key pressed - adding flower to team:', team)
              activeScene.groupBar.addReward(team, 'flower')
              console.log('Added flower to team:', team)
            }
            if (e.key.toLowerCase() === 's') {
              console.log('S key pressed - adding star to team:', team)
              activeScene.groupBar.addReward(team, 'star')
              console.log('Added star to team:', team)
            }
            if (e.key.toLowerCase() === 'e') {
              console.log('E key pressed - adding earth to team:', team)
              activeScene.groupBar.addReward(team, 'earth')
              console.log('Added earth to team:', team)
            }
            if (e.key.toLowerCase() === 'r') {
              console.log('R key pressed - resetting all scores')
              activeScene.groupBar.resetAll()
              console.log('Reset all team scores')
            }
          } else {
            console.log('No groupBar found in active scene')
          }
        } else {
          console.log('No active scene found')
        }
      }

      // Ctrl/Cmd+S保存
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {
        e.preventDefault()
        if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
          const activeScene = this.scene.get(this.activeSceneKey) as any
          if (activeScene && activeScene.groupBar) {
            activeScene.groupBar.save()
            console.log('Saved group scores')
          }
        }
      }
    })
  }

  switchToMode(modeKey) {
    console.log('Switching to mode:', modeKey)
    this.currentMode = modeKey

    // 映射
    const sceneMap: { [key: string]: string } = {
      'mode_a': 'ModeAScene',
      'mode_b': 'ModeBScene',
      'mode_c': 'ModeCScene'
    }
    const newScene = sceneMap[modeKey]
    console.log('Target scene:', newScene)

    // 如果当前已有活动场景，先安全停止
    if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
      console.log('Stopping current scene:', this.activeSceneKey)
      this.scene.stop(this.activeSceneKey)
    }

    // 启动/重启新场景
    if (newScene) {
      this.activeSceneKey = newScene
      if (this.mainUI) this.mainUI.setVisible(false)
      console.log('Starting new scene:', newScene)
      this.scene.start(newScene, { rangeMode: this.rangeMode, totalRounds: this.totalRounds })
      // 让新场景显示在最上层，避免被 MainScene 遮挡
      this.scene.bringToTop(newScene)
      console.log('Scene switch completed')
    }
  }

  setRangeMode(range) {
    console.log('Setting range mode:', range)
    this.rangeMode = range

    // 更新按钮样式 - 使用存储的数据属性
    this.teacherBar.list.forEach((child) => {
      if (child.getData && child.getData('rangeKey')) {
        const isActive = child.getData('rangeKey') === range
        console.log(`Updating range button ${child.getData('rangeKey')}, active: ${isActive}`)
        child.setStyle({
          color: isActive ? '#FDE047' : '#D9E8FF',
          backgroundColor: isActive ? '#374151' : '#2D3748'
        })
      }
    })

    // 通知当前活动场景
    if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
      console.log('Notifying active scene of range change:', this.activeSceneKey)
      this.scene.get(this.activeSceneKey).events.emit('rangeChanged', range)
    }
  }

  toggleFullscreen() {
    if (this.scale.isFullscreen) {
      this.scale.stopFullscreen()
    } else {
      this.scale.startFullscreen()
    }
  }

  toggleSound() {
    this.soundEnabled = !this.soundEnabled
    console.log('Sound enabled:', this.soundEnabled)
    this.sound.mute = !this.soundEnabled

    // 同时控制我们的音效工具
    SoundUtils.setEnabled(this.soundEnabled)

    // 播放测试音效确认状态
    if (this.soundEnabled) {
      SoundUtils.playClick()
    }
  }

  setRounds(val) {
    console.log('Setting total rounds to:', val)
    this.totalRounds = val

    // 更新按钮高亮 - 使用存储的数据属性
    this.teacherBar.list.forEach((child) => {
      if (child.getData && child.getData('roundsValue')) {
        const isActive = child.getData('roundsValue') === val
        console.log(`Updating rounds button ${child.getData('roundsValue')}, active: ${isActive}`)
        child.setStyle({
          color: isActive ? '#FDE047' : '#D9E8FF',
          backgroundColor: isActive ? '#374151' : '#2D3748'
        })
      }
    })

    // 通知活动场景轮次变更
    if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
      console.log('Notifying active scene of rounds change:', this.activeSceneKey)
      this.scene.get(this.activeSceneKey).events.emit('roundsChanged', val)
    }
  }

  // 处理窗口大小变化
  handleResize(gameSize) {
    console.log(`MainScene resize: ${gameSize.width}x${gameSize.height}`)

    // 响应式缩放已在ResponsiveUtils中禁用
    this.responsive.applyGlobalScale(this)

    // 通知活动的子场景
    if (this.activeSceneKey && this.scene.isActive(this.activeSceneKey)) {
      const activeScene = this.scene.get(this.activeSceneKey) as any
      if (activeScene && activeScene.handleResize) {
        activeScene.handleResize(gameSize)
      }
    }
  }

  showHelp() {
    // 启动帮助场景作为覆盖层
    if (!this.scene.isActive('HelpScene')) {
      this.scene.launch('HelpScene')
    }
  }
}
